package com.mrd.gtimp.business.action;

import com.mrd.constant.MsgConstants;
import com.mrd.constant.RoleConstants;
import com.mrd.constant.SystemConstants;
import com.mrd.exception.QueryException;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.config.web.json.annotation.JField;
import com.mrd.framework.config.web.json.annotation.Json;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.FilterGroupOption;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.business.entity.CheckingGoods;
import com.mrd.gtimp.business.entity.Commodity;
import com.mrd.gtimp.business.entity.CompanyQp;
import com.mrd.gtimp.business.entity.Declaration;
import com.mrd.gtimp.business.service.CheckingGoodsBiz;
import com.mrd.gtimp.business.service.CompanyQpBiz;
import com.mrd.gtimp.business.service.DeclarationBiz;
import com.mrd.util.ReflectUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import static com.mrd.util.AdminUtil.checkRight;

/**
 * 线下查货服务功能模块
 *
 * @author lenovo
 */

@Controller
@RequestMapping("/business")
public class CheckingGoodsAction {

    private static final long serialVersionUID = 999891062477500580L;

    @Resource
    private CheckingGoodsBiz checkingGoodsBiz;

    @Resource
    private DeclarationBiz declarationBiz;

    @Resource
    private CompanyQpBiz companyQpBiz;

    /**
     * 返回前台的结果变量，格式为[[显示值，真实值],[显示值1，真实值1],...]
     */
    private String[][] results;

    /**
     * 主页面
     */
    @RequestMapping("/checkingGoods-main")
    public String main() {
        return "/gtimp/checkingGoods/main";
    }

    /**
     * 查货列表
     */
    @RequestMapping("/checkingGoods-findList")
    @ResponseBody
    @Json({@JField("checking_id"), @JField("companyQp.cOMPANY_NAME"), @JField("route"), @JField("declaration_no"), @JField("container_info"), @JField("container_no"),
            @JField("heap_position"), @JField("camera_position"), @JField("check_official"), @JField("seal_no"), @JField("commodity.name"), @JField("specifications"),
            @JField("check_items"), @JField("declaration_weight"), @JField("receipt_check_notice"), @JField("status"), @JField("save_time")})
    public Page<CheckingGoods> findList(Jqgrid jqgrid) {
        Filter filters = jqgrid.getFilters();
        String status = HttpUtils.getParam("status");
        try {
            if (null == filters) {
                filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
            }
            String hql = "from com.mrd.gtimp.business.entity.CheckingGoods checkingGoods where 1=1";
            if (StringUtils.isNotEmpty(status)) {
                hql += " and checkingGoods.status='" + status + "' ";
            }
            String whereCase = "";
            if (null != filters.getRules() && filters.getRules().size() > 0) {
                for (SearchRule sr : filters.getRules()) {
                    String field = sr.getField();
                    Object data = sr.getData();
                    Field f = ReflectUtil.getField(sr.getField(), CheckingGoods.class);
                    boolean isDate = false;
                    if (f != null) {
                        if (f.getType().equals(Date.class)) {
                            data = "to_date('" + data + "','yyyy-MM-dd')";
                            isDate = true;
                        }
                    }
                    if (sr.getOp().equals(SearchRuleOption.eq)) {
                        whereCase = whereCase + " and checkingGoods." + field + " = '" + data + "' ";
                    } else if (sr.getOp().equals(SearchRuleOption.nc)) {
                        whereCase = whereCase + " and checkingGoods." + field + " not in ('" + data
                                + "') ";
                    } else if (sr.getOp().equals(SearchRuleOption.gt)) {
                        whereCase = whereCase + " and checkingGoods." + field
                                + (isDate ? " > " + data : " > '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.lt)) {
                        whereCase = whereCase + " and checkingGoods." + field
                                + (isDate ? " < " + data : " < '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.ge)) {
                        whereCase = whereCase + " and checkingGoods." + field
                                + (isDate ? " >= " + data : " >= '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.le)) {
                        whereCase = whereCase + " and checkingGoods." + field
                                + (isDate ? " <= " + data : " <= '" + data + "'");
                    } else {
                        whereCase = whereCase + " and checkingGoods." + field + " like '%" + data + "%' ";
                    }
                }
            }
//            Order order = new Order();
//            if (null != sidx && !"".equals(sidx)) {
//                order.add(sidx, sord);
//            }
//            for (String key : order.keySet()) {
//                whereCase = whereCase + " order by checkingGoods." + key + " "
//                        + (order.get(key) ? "desc" : "asc") + " ";
//            }
            List<CheckingGoods> checkingGoodsDtos = checkingGoodsBiz.findEntityByHql(hql + whereCase, jqgrid.getPage().getPageNumber(), jqgrid.getPage().getPageSize(), null);
            Page<CheckingGoods> page = new PageImpl<CheckingGoods>(checkingGoodsDtos);
            return page;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 新增修改页面
     */
    @RequestMapping("/checkingGoods-manage")
    public String manage(String checking_id, Model model) {
        model.addAttribute("checking_id", checking_id);
        return "/gtimp/checkingGoods/manage";
    }

    /**
     * 根据id查找
     */
    @RequestMapping("/checkingGoods-find")
    @ResponseBody
    public CheckingGoods find(CheckingGoods checkingGoods) {
        if (checkingGoods != null && StringUtils.isNotEmpty(checkingGoods.getChecking_id())) {
            try {
                checkingGoods = checkingGoodsBiz.findEntityById(checkingGoods.getChecking_id());
                return checkingGoods;
            } catch (QueryException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @RequestMapping("/checkingGoods-initContainerNoByDeclarationNo")
    public String initContainerNoByDeclarationNo(CheckingGoods checkingGoods) throws QueryException {
        if (checkingGoods != null) {
            String checking_id = checkingGoods.getChecking_id();
            String sno = checkingGoods.getDeclaration_no();
            if (StringUtils.isNotEmpty(checking_id)) {
                checkingGoods = checkingGoodsBiz.findEntityById(checking_id);
                if (checkingGoods != null) {
                    sno = checkingGoods.getDeclaration_no();
                }
            }
            if (StringUtils.isNotEmpty(sno)) {
                String hql = "from com.mrd.gtimp.business.entity.Declaration Declaration where Declaration.sno='" + sno + "'";
                List<Declaration> declarations = declarationBiz.findEntityByHql(hql, 0, 0, null);
                for (Declaration declaration : declarations) {
                    String containers = declaration.getContainer_no();
                    if (StringUtils.isNotEmpty(containers)) {
                        String[] c = containers.split(",");
                        results = new String[c.length][2];
                        for (int i = 0; i < c.length; i++) {
                            results[i][0] = c[i];
                            results[i][1] = c[i];
                        }
                    }
                }
            }

        }
        return null;
    }


    /**
     * 根据报关单号，查找商品名称
     */
    @RequestMapping("/checkingGoods-initCommoditiesByDeclarationNo")
    @ResponseBody
    public List<Commodity> initCommoditiesByDeclarationNo(CheckingGoods checkingGoods) throws QueryException {
        List<Commodity> commodityList = new ArrayList<>();
        if (null != checkingGoods) {
            String checking_id = checkingGoods.getChecking_id();
            String sno = checkingGoods.getDeclaration_no();
            if (StringUtils.isNotEmpty(checking_id)) {
                checkingGoods = checkingGoodsBiz.findEntityById(checking_id);
                if (checkingGoods != null) {
                    sno = checkingGoods.getDeclaration_no();
                }
            }
            if (StringUtils.isNotEmpty(sno)) {
                String hql = "from com.mrd.gtimp.business.entity.Declaration Declaration where Declaration.sno='" + sno + "'";
                List<Declaration> declarations = declarationBiz.findEntityByHql(hql, 0, 0, null);
                for (Declaration declaration : declarations) {
                    commodityList = declaration.getCommodities();
                    results = new String[commodityList.size()][2];
                    for (int i = 0; i < commodityList.size(); i++) {
                        Commodity commodity = commodityList.get(i);
                        results[i][0] = commodity.getName();
                        results[i][1] = commodity.getId();
                    }
                }
                return commodityList;
            }

        }
        return null;
    }

    /**
     * 根据报关单号，查找经营单位
     */
    @RequestMapping("/checkingGoods-initCompanyByDeclarationNo")
    @ResponseBody
    public List<CompanyQp> initCompanyByDeclarationNo(CheckingGoods checkingGoods) {
        List<CompanyQp> companyQps = new ArrayList<>();
        if (null != checkingGoods) {
            String sno = checkingGoods.getDeclaration_no();
            if (StringUtils.isNotEmpty(sno)) {
                String hql = "from com.mrd.gtimp.business.entity.Declaration Declaration where Declaration.sno='" + sno + "'";
                List<Declaration> declarations = declarationBiz.findEntityByHql(hql, 0, 0, null);
                for (Declaration declaration : declarations) {
                    String company_no = declaration.getCompany_co();
                    //String company_name = declaration.getCompany_name();
                    String company_hql = "from com.mrd.gtimp.business.entity.CompanyQp CompanyQp where CompanyQp.companyCode='" + company_no + "'";
                    companyQps = companyQpBiz.findEntityByHql(company_hql, 0, 0, null);
                    for (CompanyQp companyQp : companyQps) {
                        checkingGoods.setCompanyQp(companyQp);
                    }
                }
                return companyQps;
            }
        }
        return null;
    }


    /**
     * 新增或修改
     */
    @RequestMapping("/checkingGoods-saveOrUpdate")
    @ResponseBody
    public Result saveOrUpdate(CheckingGoods checkingGoods) {
        Result msg;
        if (checkRight(RoleConstants.SUP_CUSTOMER_SAVE)) {
            try {
                if (StringUtils.isEmpty(checkingGoods.getChecking_id())) { // 新增操作
                    checkingGoods.setChecking_id(null);
                } else { // 修改操作
                }
                checkingGoods.setSave_time(new Date());
                //// TODO: 2016/8/29 companyQp 下拉框bug
                checkingGoodsBiz.saveOrupdateEntity(checkingGoods);
                msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.SAVE_FAIL + e.getMessage());
            }
            return msg;
        }
        return Result.newFailInstance(SystemConstants.ROLE_FAIL);
    }


    public String[][] getResults() {
        return results;
    }

    public void setResults(String[][] results) {
        this.results = results;
    }
}
